<template>
  <div class="user-dashboard">
    <h2>个人健康概览</h2>
    <div class="dashboard-cards">
      <div class="card health-score">
        <div class="card-header">
          <div class="card-icon score-icon">
            <i class="iconfont icon-star"></i>
          </div>
          <h3>最新健康评分</h3>
        </div>
        <div class="card-content">
          <div class="score-value">{{ loading ? '加载中...' : dashboardData.healthScore }}</div>
          <div class="score-status">{{ loading ? '加载中...' : (dashboardData.healthScore >= 80 ? '良好' : dashboardData.healthScore >= 60 ? '一般' : '较差') }}</div>
        </div>
      </div>
      <div class="card health-assessment">
        <div class="card-header">
          <div class="card-icon assessment-icon">
            <i class="iconfont icon-heartbeat"></i>
          </div>
          <h3>健康评估</h3>
        </div>
        <div class="card-content">
          <div class="risk-value" :style="{ color: getRiskLevelColor(dashboardData.riskPercentage) }">{{ loading ? '加载中...' : dashboardData.riskLevel }}</div>
          <div class="risk-percentage" :style="{ color: getRiskLevelColor(dashboardData.riskPercentage) }">{{ loading ? '加载中...' : dashboardData.riskPercentage }}%</div>
        </div>
      </div>
      <div class="card bmi-index">
        <div class="card-header">
          <div class="card-icon bmi-icon">
            <i class="iconfont icon-weight"></i>
          </div>
          <h3>BMI指数</h3>
        </div>
        <div class="card-content">
          <div class="bmi-value">{{ loading ? '加载中...' : dashboardData.bmi }}</div>
          <div class="bmi-status">{{ loading ? '加载中...' : dashboardData.bmiStatus }}</div>
        </div>
      </div>
      <div class="card record-count">
        <div class="card-header">
          <div class="card-icon record-icon">
            <i class="iconfont icon-history"></i>
          </div>
          <h3>记录次数</h3>
        </div>
        <div class="card-content">
          <div class="count-value">{{ loading ? '加载中...' : dashboardData.recordCount }}</div>
          <div class="count-text">次健康数据记录</div>
        </div>
      </div>
    </div>
    
    <div class="features-section">
      <h3>功能区</h3>
      <div class="feature-cards">
        <router-link to="/user/health-data" class="feature-card">
          <div class="feature-icon health-data">
            <i class="iconfont icon-data"></i>
          </div>
          <h4>健康数据录入</h4>
          <p>录入和管理您的健康数据</p>
        </router-link>
        
        <router-link to="/user/data-history" class="feature-card">
          <div class="feature-icon history">
            <i class="iconfont icon-history"></i>
          </div>
          <h4>历史记录</h4>
          <p>查看所有健康数据记录</p>
        </router-link>
        
        <router-link to="/user/predictions" class="feature-card">
          <div class="feature-icon prediction">
            <i class="iconfont icon-predict"></i>
          </div>
          <h4>预测结果</h4>
          <p>查看健康风险预测分析</p>
        </router-link>
        
        <router-link to="/user/profile" class="feature-card">
          <div class="feature-icon profile">
            <i class="iconfont icon-user"></i>
          </div>
          <h4>个人信息</h4>
          <p>管理您的账户信息</p>
        </router-link>
      </div>
    </div>
    
    <div class="links-section">
      <h3>链接导航</h3>
      <div class="links-container">
        <a href="https://jiankang.cctv.com/" target="_blank" class="link-card health-news">
          <h4>健康资讯</h4>
          <p>国家卫健委官方健康资讯</p>
        </a>
        
        <a href="http://www.layeyese.com/" target="_blank" class="link-card yangsheng">
          <h4>中医养生</h4>
          <p>中国中医科学院养生指南</p>
        </a>
        
        <a href="https://www.shdmu.com/web/details/booking?coid=31" target="_blank" class="link-card hospital">
          <h4>医院挂号</h4>
          <p>大连医科大学附属第二医院预约挂号平台</p>
        </a>
        
        <a href="https://www.chinacdc.cn/" target="_blank" class="link-card cdc">
          <h4>疾病预防</h4>
          <p>中国疾控中心预防指南</p>
        </a>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import api from '../../utils/axiosConfig'
import fastApi from '../../utils/fastApiConfig'

export default {
  name: 'UserDashboard',
  setup() {
    const userStore = useUserStore()
    const dashboardData = ref({
      healthScore: 85,
      riskLevel: '低风险',
      riskPercentage: 12,
      bmi: 23.5,
      bmiStatus: '正常',
      recordCount: 24
    })
    const loading = ref(false)
    
    // 获取风险等级颜色
    const getRiskLevelColor = (riskPercentage) => {
      if (riskPercentage < 30) return '#67c23a'; // 绿色 - 低风险
      if (riskPercentage < 60) return '#e6a23c'; // 橙色 - 中风险
      if (riskPercentage < 90) return '#f56c6c'; // 红色 - 高风险
      return '#d9363e'; // 深红色 - 建议就医
    }

    // 计算风险等级
    const calculateRiskLevel = (riskPercentage) => {
      if (riskPercentage < 30) return '低风险';
      if (riskPercentage < 60) return '中风险';
      if (riskPercentage < 90) return '高风险';
      return '建议就医';
    }

    // 计算BMI状态
    const calculateBMIStatus = (bmi) => {
      if (bmi < 18.5) return '偏瘦';
      if (bmi < 24) return '正常';
      if (bmi < 28) return '超重';
      return '肥胖';
    }

    // 计算健康评分
    const calculateHealthScore = (riskPercentage, bmi) => {
      let riskScore = 100 - riskPercentage; // 基于风险的得分
      let bmiScore = 85; // 基础BMI得分
      
      // 根据BMI调整得分
      if (bmi >= 18.5 && bmi < 24) {
        bmiScore = 100; // 正常BMI满分
      } else if (bmi >= 24 && bmi < 28) {
        bmiScore = 70; // 超重减分
      } else if (bmi >= 28) {
        bmiScore = 50; // 肥胖减分
      } else if (bmi < 18.5) {
        bmiScore = 60; // 偏瘦减分
      }
      
      // 综合得分（70%风险 + 30%BMI）
      return Math.round(riskScore * 0.7 + bmiScore * 0.3);
    }

    const fetchDashboardData = async () => {
      loading.value = true
      try {
        // 添加详细调试信息
        console.log('User Store 状态:', {
          isLoggedIn: userStore.isLoggedIn,
          role: userStore.role,
          username: userStore.username,
          userInfoKeys: userStore.userInfo ? Object.keys(userStore.userInfo) : 'null'
        });
        
        // 查看localStorage中的所有用户相关数据
        const userLoggedIn = localStorage.getItem('userLoggedIn');
        const userRole = localStorage.getItem('userRole');
        const userName = localStorage.getItem('userName');
        const userInfoStr = localStorage.getItem('userInfo');
        
        console.log('LocalStorage 用户数据:', {
          userLoggedIn,
          userRole,
          userName,
          hasUserInfo: !!userInfoStr
        });
        
        // 如果有userInfo，尝试解析并显示所有键
        if (userInfoStr) {
          try {
            const parsedUserInfo = JSON.parse(userInfoStr);
            console.log('解析后的userInfo内容:', Object.keys(parsedUserInfo));
            console.log('完整userInfo对象:', parsedUserInfo);
          } catch (e) {
            console.error('解析userInfo失败:', e);
            console.log('原始userInfo字符串:', userInfoStr);
          }
        }
        
        // 尝试从多个可能的来源获取用户ID
        let userId = null;
        
        // 1. 从userStore的userInfo中获取 - 检查所有可能的ID字段
        if (userStore && userStore.userInfo) {
          // 打印userInfo的完整内容以便调试
          console.log('当前userInfo对象内容:', userStore.userInfo);
          
          // 首先检查外层userInfo对象
          const possibleIdFields = ['userId', 'user_id', 'id', 'uid', 'accountId', 'userid'];
          for (const field of possibleIdFields) {
            if (userStore.userInfo[field] !== undefined && userStore.userInfo[field] !== null && userStore.userInfo[field] !== '') {
              userId = userStore.userInfo[field];
              console.log(`从userInfo的${field}字段获取到用户ID:`, userId);
              break;
            }
          }
          
          // 如果外层没找到，检查嵌套的userInfo对象
          if (!userId && userStore.userInfo.userInfo) {
            console.log('检查嵌套的userInfo对象');
            console.log('嵌套userInfo对象内容:', userStore.userInfo.userInfo);
            // 打印嵌套userInfo对象的所有键
            if (userStore.userInfo.userInfo) {
              console.log('嵌套userInfo对象的所有键:', Object.keys(userStore.userInfo.userInfo));
              // 打印嵌套userInfo对象的完整字符串表示
              console.log('嵌套userInfo对象的字符串表示:', JSON.stringify(userStore.userInfo.userInfo));
            }
            // 尝试从嵌套对象获取ID
            for (const field of possibleIdFields) {
              if (userStore.userInfo.userInfo[field] !== undefined && 
                  userStore.userInfo.userInfo[field] !== null && 
                  userStore.userInfo.userInfo[field] !== '') {
                userId = userStore.userInfo.userInfo[field];
                console.log(`从嵌套userInfo的${field}字段获取到用户ID:`, userId);
                break;
              }
            }
            
            // 额外尝试直接获取嵌套对象中的任何数字值作为ID
            if (!userId) {
              console.log('尝试直接从嵌套userInfo对象中查找任何数字值作为ID');
              const nestedInfo = userStore.userInfo.userInfo;
              for (const [key, value] of Object.entries(nestedInfo)) {
                if (typeof value === 'number' && value > 0) {
                  userId = value;
                  console.log(`从嵌套userInfo的${key}字段获取到用户ID(数字值):`, userId);
                  break;
                }
                // 也尝试字符串类型的数字
                if (typeof value === 'string' && !isNaN(parseInt(value, 10)) && parseInt(value, 10) > 0) {
                  userId = parseInt(value, 10);
                  console.log(`从嵌套userInfo的${key}字段获取到用户ID(字符串数字):`, userId);
                  break;
                }
              }
            }
          }
        }
        
        // 2. 如果userStore中没有，尝试直接从localStorage的userInfo解析
        if (!userId && userInfoStr) {
          try {
            const parsedUserInfo = JSON.parse(userInfoStr);
            console.log('解析localStorage的userInfo对象:', parsedUserInfo);
            
            // 首先检查外层对象
            const possibleIdFields = ['userId', 'user_id', 'id', 'uid', 'accountId', 'userid'];
            for (const field of possibleIdFields) {
              if (parsedUserInfo[field] !== undefined && parsedUserInfo[field] !== null && parsedUserInfo[field] !== '') {
                userId = parsedUserInfo[field];
                console.log(`从localStorage的userInfo中${field}字段获取到用户ID:`, userId);
                break;
              }
            }
            
            // 如果外层没找到，检查嵌套的userInfo对象
            if (!userId && parsedUserInfo.userInfo) {
              console.log('检查localStorage中嵌套的userInfo对象');
              // 打印嵌套userInfo对象的所有键
              console.log('localStorage嵌套userInfo对象的所有键:', Object.keys(parsedUserInfo.userInfo));
              // 打印嵌套userInfo对象的完整字符串表示
              console.log('localStorage嵌套userInfo对象的字符串表示:', JSON.stringify(parsedUserInfo.userInfo));
              
              // 尝试从嵌套对象获取ID
              for (const field of possibleIdFields) {
                if (parsedUserInfo.userInfo[field] !== undefined && 
                    parsedUserInfo.userInfo[field] !== null && 
                    parsedUserInfo.userInfo[field] !== '') {
                  userId = parsedUserInfo.userInfo[field];
                  console.log(`从localStorage嵌套userInfo的${field}字段获取到用户ID:`, userId);
                  break;
                }
              }
              
              // 额外尝试直接获取嵌套对象中的任何数字值作为ID
              if (!userId) {
                console.log('尝试从localStorage嵌套userInfo对象中查找任何数字值作为ID');
                const nestedInfo = parsedUserInfo.userInfo;
                for (const [key, value] of Object.entries(nestedInfo)) {
                  if (typeof value === 'number' && value > 0) {
                    userId = value;
                    console.log(`从localStorage嵌套userInfo的${key}字段获取到用户ID(数字值):`, userId);
                    break;
                  }
                  // 也尝试字符串类型的数字
                  if (typeof value === 'string' && !isNaN(parseInt(value, 10)) && parseInt(value, 10) > 0) {
                    userId = parseInt(value, 10);
                    console.log(`从localStorage嵌套userInfo的${key}字段获取到用户ID(字符串数字):`, userId);
                    break;
                  }
                }
              }
            }
          } catch (e) {
            console.error('解析userInfo失败:', e);
          }
        }
        
        // 确保userId是有效的数字
        userId = userId ? (typeof userId === 'string' ? parseInt(userId, 10) : Number(userId)) : null;
        console.log('最终确定的用户ID:', userId);
        
        // 只检查用户是否已登录标记，不严格要求userId（可能是新用户）
        if (userLoggedIn !== 'true') {
          console.warn('用户未登录');
          dashboardData.value = {
            healthScore: '-',
            riskLevel: '请登录',
            riskPercentage: '-',
            bmi: '-',
            bmiStatus: '请登录',
            recordCount: 0
          };
          loading.value = false;
          return;
        }
        
        console.log('使用的用户ID:', userId);

        // 只有当userId有效时才进行API调用
        if (userId && !isNaN(userId)) {
          // 1. 获取健康风险数据
          try {
            const healthRiskResponse = await api.get(`http://localhost:8080/api/health-risk/getByUserId?userId=${userId}`);
            if (healthRiskResponse.data && healthRiskResponse.data.length > 0) {
              // 获取最新的风险记录
              const latestRisk = healthRiskResponse.data.sort((a, b) => 
                new Date(b.predictTime) - new Date(a.predictTime)
              )[0];
              
              // 设置风险百分比（转换为百分比并保留两位小数）
              const riskPercentage = Math.round(latestRisk.cardioRisk * 100 * 100) / 100;
              dashboardData.value.riskPercentage = riskPercentage;
              dashboardData.value.riskLevel = calculateRiskLevel(riskPercentage);
            } else {
              console.log('未找到健康风险数据');
            }
          } catch (riskError) {
            console.error('获取健康风险数据失败:', riskError);
          }

          // 2. 获取健康指标数据（包含BMI和记录数）
          try {
            const healthIndicatorResponse = await api.get(`http://localhost:8080/api/health-indicator/getByUserId?userId=${userId}`);
            if (healthIndicatorResponse.data && healthIndicatorResponse.data.length > 0) {
              const indicators = healthIndicatorResponse.data;
              
              // 记录次数
              dashboardData.value.recordCount = indicators.length;
              
              // 获取最新的BMI
              const latestIndicator = indicators.sort((a, b) => 
                new Date(b.submitTime) - new Date(a.submitTime)
              )[0];
              
              if (latestIndicator.bmi) {
                dashboardData.value.bmi = latestIndicator.bmi;
                dashboardData.value.bmiStatus = calculateBMIStatus(latestIndicator.bmi);
              }
            } else {
              console.log('未找到健康指标数据');
              dashboardData.value.recordCount = 0;
            }
          } catch (indicatorError) {
            console.error('获取健康指标数据失败:', indicatorError);
          }
        } else {
          console.warn('未找到有效的用户ID，无法获取健康数据');
          dashboardData.value.recordCount = 0;
        }

        // 3. 计算健康评分
        dashboardData.value.healthScore = calculateHealthScore(
          dashboardData.value.riskPercentage,
          dashboardData.value.bmi
        );

        console.log('仪表盘数据更新成功:', dashboardData.value);
      } catch (error) {
        console.error('获取仪表盘数据失败:', error);
      } finally {
        loading.value = false;
      }
    }
    
    onMounted(() => {
      fetchDashboardData()
    })
    
    return {
      dashboardData,
      loading,
      getRiskLevelColor
    }
  }
}
</script>

<style scoped>
/* 引入图标库 */
/* 移除外部字体CSS引用，使用项目内置字体 */

.user-dashboard {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.user-dashboard h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
}

.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.card {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  border-color: #dcdfe6;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.card-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 20px;
  color: #fff;
}

.score-icon {
  background-color: #67c23a;
}

.assessment-icon {
  background-color: #409eff;
}

.bmi-icon {
  background-color: #e6a23c;
}

.record-icon {
  background-color: #909399;
}

.card h3 {
  color: #606266;
  font-size: 16px;
  margin: 0;
  font-weight: 500;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.score-value, .risk-value, .bmi-value, .count-value {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 8px;
}

.score-status, .risk-percentage, .bmi-status, .count-text {
  font-size: 14px;
}

.score-value, .score-status {
  color: #67c23a;
}

/* 风险等级颜色将通过动态绑定设置 */
.risk-value, .risk-percentage {
  /* 基础颜色，会被动态样式覆盖 */
  color: #409eff;
}

.bmi-value, .bmi-status {
  color: #e6a23c;
}

.count-value, .count-text {
  color: #909399;
}

/* 功能区样式 */
.features-section {
  margin-bottom: 30px;
}

.features-section h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
}

.feature-card {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 25px;
  text-align: center;
  text-decoration: none;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.feature-card:hover {
  border-color: #409eff;
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(64, 158, 255, 0.2);
}

.feature-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
  font-size: 28px;
  color: #fff;
}

.feature-icon.health-data {
  background-color: #67c23a;
}

.feature-icon.history {
  background-color: #409eff;
}

.feature-icon.prediction {
  background-color: #e6a23c;
}

.feature-icon.profile {
  background-color: #f56c6c;
}

.feature-card h4 {
  color: #303133;
  font-size: 18px;
  margin-bottom: 10px;
  font-weight: 500;
}

.feature-card p {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

/* 链接导航样式 */
.links-section {
  margin-bottom: 20px;
}

.links-section h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 600;
}

.links-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
}

.link-card {
  background-color: #f5f7fa;
  border-left: 4px solid #409eff;
  border-radius: 8px;
  padding: 20px;
  text-decoration: none;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.link-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.1) 100%);
  z-index: 0;
}

.link-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.link-card.health-news {
  border-left-color: #67c23a;
  background-color: rgba(103, 194, 58, 0.05);
}

.link-card.yangsheng {
  border-left-color: #e6a23c;
  background-color: rgba(230, 162, 60, 0.05);
}

.link-card.hospital {
  border-left-color: #f56c6c;
  background-color: rgba(245, 108, 108, 0.05);
}

.link-card.cdc {
  border-left-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.link-card h4 {
  color: #303133;
  font-size: 16px;
  margin-bottom: 8px;
  font-weight: 500;
  position: relative;
  z-index: 1;
}

.link-card p {
  color: #909399;
  font-size: 13px;
  margin: 0;
  position: relative;
  z-index: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-cards,
  .feature-cards,
  .links-container {
    grid-template-columns: 1fr;
  }
  
  .user-dashboard h2 {
    font-size: 20px;
  }
  
  .features-section h3,
  .links-section h3 {
    font-size: 18px;
  }
}
</style>